import { Request, queryParams } from './utils/util.js'

App({
  onLaunch: function (options) {
    let inviter = options.query.inviter || 0

    let scene = options.query.scene
    if (scene) {
      scene = decodeURIComponent(scene)
      scene = queryParams(scene)
      wx.showModal({
        title: '',
        content: JSON.stringify(scene),
      })
      if (scene.f === 'i') { //来自邀请
        inviter = scene.iv //邀请人
      }
    }

    wx.getSystemInfo({
      success: res => {
        this.systemInfo = res
      }
    })

    let self = this
    // 登录
    wx.login({
      success: res => {
        let request = new Request()
        request.post('login', res => {
          if(res.success){
            self.globalData.isLogin = true
            let token = res.data.token
            let user = res.data.user
            if(!(user instanceof Object)) {
              user = JSON.parse(user)
            }
            wx.setStorage({key : 'token', data : token})
            wx.setStorage({
              key: 'userinfo',
              data: user,
            })
            
            self.globalData.userInfo = user
            self.getUserInfo()

            if (inviter > 0) {
              request.post('visit/follow', res => {
                
              }, { userId: inviter })
            }
          }
        }, { code: res.code, inviter: inviter})
      }
    })
  },


  getUserInfo () {
    let self = this
    // 获取用户信息
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          wx.getUserInfo({
            success: data => {
              let request = new Request()
              let params = {
                encryptedData: data.encryptedData,
                iv: data.iv,
                rawData: data.rawData,
                signature: data.signature
              }

              request.post('userinfo', res => {
                if (res.success) {
                  let userInfo = res.data
                  userInfo = Object.assign(self.globalData.userInfo, userInfo)
                  self.globalData.userInfo = userInfo
                  wx.setStorage({
                    key: 'userinfo',
                    data: userInfo,
                  })
                }
              }, params)

              let newInfo = Object.assign(self.globalData.userInfo, { nickname: data.userInfo.nickName, avatar: data.userInfo.avatarUrl, sex: data.userInfo.gender })
              self.globalData.userInfo = newInfo
              wx.setStorage({
                key: 'userinfo',
                data: newInfo
              })
            }
          })
        } else {
          wx.navigateTo({
            url: '/pages/auth/index'
          })
        }
      }
    })
  },

  systemInfo : null,
  
  globalData: {
    userInfo: null,
    userNumber : null,
    city : null,
    isLogin : false
  },

  newPublish : false
})